package com.me.web;

import com.me.dao.IUserDao;
import com.me.dao.impl.UserDao;
import com.me.domain.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends BaseServlet {
    @Override
	protected void doPost() throws ServletException, IOException {
		String url = null;
		String msg = null;
		String realcode = getSesAttr("realcode").toString();
		String inputcode = getParam("checkcode");

		if (realcode.equalsIgnoreCase(inputcode)){
			IUserDao userDao = new UserDao();
			try {
				User user = userDao.getByName(getParam("name"));
				if (user==null){
					url = "/login.jsp";
					msg = "用户名不存在";
				}else if(!user.getPwd().equals(getParam("pwd"))){
					url = "/login.jsp";
					msg = "密码错误";
				}else {
					setSesAttr("user",user);
					msg = "登录成功";
					if (user.getRole().equals("admin")){
						url = "./index.jsp";
					} else if (user.getRole().equals("customer")) {
						url = "./index.jsp";
					} else {
						url = "/login.jsp";
						msg = "身份错误，请联系管理员";
						clearSes();
					}
				}
			}catch (Exception e){
				url = "/login.jsp";
				msg = e.toString();
			}
		}else {
			url = "/login.jsp";
			msg = "验证码输入有误";
		}
		setReqAttr("msg",msg);
		forward(url);
	}

    @Override
    protected void doGet() throws ServletException, IOException {

    }
}
